package com.loongtech.bi.action.authManagement;

import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Utils;
import org.datanucleus.util.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Author: yuri
 * Description: 系统用户管理
 * Date: 14:27 2017/5/3
 */
@RestController
@Scope("prototype")
@RequestMapping("/user")
public class SysUserAction implements Serializable {
    private static final long serialVersionUID = 1L;
    @Resource
    private Session session;
    @Resource
    private SysLogManager sysLogManager;
    @Resource
    private SysUserManager sysUserManager;


    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> list() {
        List<EntitySysUser> list;
        try {
            list = sysUserManager.findByQuery("from EntitySysUser order by department, description, id ");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> register(EntitySysUser user) {
        // 判断用户username是否已经被注册
        if (null != sysUserManager.getBy(EntitySysUser.K.username, user.getUsername())) {
            return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
        }
        if (user.getPassword() != null && !passwordCheck(user.getPassword())) {
            return new ResultData<>(RetCode.ePasswordFormatError.getErrorcode(), RetCode.ePasswordFormatError.getErrorMsg());
        }
        // 注册用户
        Integer userId = sysUserManager.register(user);
        if (null != userId && userId > 0) {
            sysLogManager.addLog(session.getUserName(), user.getUsername() + "用户注册成功");
            return ResultData.success();
        } else {
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modify(EntitySysUser user) {
        if (!StringUtils.isEmpty(user.getPassword()) && !passwordCheck(user.getPassword())) {
            return new ResultData<>(RetCode.ePasswordFormatError.getErrorcode(), RetCode.ePasswordFormatError.getErrorMsg());
        }
        EntitySysUser cur = sysUserManager.get(user.getId());
        try {
            if (cur != null) {
                if (StringUtils.isEmpty(user.getPassword())) {
                    user.setPassword(cur.getPassword());
                } else {
                    user.setPassword(Utils.md5(user.getPassword()));
                }

                sysUserManager.merge(user);
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eModuleEmpty.getErrorcode(), RetCode.eModuleEmpty.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delete(int userId) {
        try {
            EntitySysUser cur = sysUserManager.get(userId);
            if (null != cur && cur.getIsAdmin()) {
                return new ResultData<>(RetCode.eAdminErrorCommit.getErrorcode(), RetCode.eAdminErrorCommit.getErrorMsg());
            }
            if (null != cur && cur.getUsername().equals(session.getUserName())) {
                return new ResultData<>(RetCode.eSelfErrorCommit.getErrorcode(), RetCode.eSelfErrorCommit.getErrorMsg());
            }
            if (null != cur) {
                sysUserManager.removeById(userId);
                sysLogManager.addLog(session.getUserName(), "用户删除成功!userId=" + userId);
                return ResultData.success();
            }
            return new ResultData<>(RetCode.eModuleEmpty.getErrorcode(), RetCode.eModuleEmpty.getErrorMsg());
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "reset.do", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<Integer, String> reset(int userId) {
        EntitySysUser cur = sysUserManager.get(userId);
        if (null != cur && cur.getIsAdmin()) {
            return RetCode.retCodeToMap(RetCode.eAdminErrorCommit);
        }
        if (null != cur && cur.getUsername().equals(session.getUserName())) {
            return RetCode.retCodeToMap(RetCode.eSelfErrorCommit);
        }
        if (null != cur && sysUserManager.resetPassword(userId)) {
            sysLogManager.addLog(session.getUserName(), "用户重置密码成功!userId=" + userId);
            return RetCode.retCodeToMap(RetCode.eSuccess);
        } else {
            sysLogManager.addLog(session.getUserName(), "用户重置密码失败!userId=" + userId);
            return RetCode.retCodeToMap(RetCode.eOtherException);
        }
    }

    private boolean passwordCheck(String password) {
        // 密码验证规则
        String regEx = "((?=.*\\d)(?=.*\\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^.{8,16}$";
        return Pattern.matches(regEx, password);
    }
}